import 'package:encrypt/encrypt.dart' as encrypt;
import 'dart:convert';

void main() {
  // 测试解密功能
  testDecryption();
}

void testDecryption() {
  print('🔓 Testing decryption...');
  
  // 使用相同的密钥和IV
  const aesKey = '12345678901234567890123456789012';
  const aesIv = '1234567890123456';
  
  final encrypter = encrypt.Encrypter(
    encrypt.AES(
      encrypt.Key.fromUtf8(aesKey),
      mode: encrypt.AESMode.cbc,
    ),
  );
  
  final iv = encrypt.IV.fromUtf8(aesIv);
  
  // 从服务器得到的加密数据
  const encryptedData = "ugLUz2Roa6d4SK4913utMwVb7i3b8RoPEpIaOpOXvaWBaU9SBPtw14tP2nkouLFoAetRSbJQXS1GTuKkhqYKi1zEj4XY2t7RveDWpP/Az+wZ/xgoIGl3dLTnbDWhU+G1SH/3IMh2J6xiosVYiO2Vpd1vrmpah7amyTFgO06eqqHKStobsD3haoj+5M9+BTUytFcPtDJz+FhbEFFRtOE/WpKyO5dRE49V3HnDPU2mobgz4smf+c8bdPQNrGPbHoV7G2a/X70EW8k+Pb+WhRBksjnZdds8AyTKAHqs425T9nqXEErOBBs/9IylhnN41ufWS3rrIfYN9T7nNLb1W2gRMg==";
  
  try {
    // 解密
    final decrypted = encrypter.decrypt64(encryptedData, iv: iv);
    print('✅ Decryption successful!');
    print('📄 Decrypted text: $decrypted');
    
    // 解析JSON
    final jsonData = jsonDecode(decrypted);
    print('📄 Parsed JSON: $jsonData');
    print('📄 JSON type: ${jsonData.runtimeType}');
    
    // 检查字段
    if (jsonData is Map<String, dynamic>) {
      print('🔍 Field access test:');
      print('  success: ${jsonData['success']}');
      print('  message: ${jsonData['message']}');
      print('  data: ${jsonData['data']}');
      
      if (jsonData['data'] != null) {
        final data = jsonData['data'];
        print('  data type: ${data.runtimeType}');
        if (data is Map<String, dynamic>) {
          print('  token: ${data['token']}');
          print('  user_info: ${data['user_info']}');
        }
      }
    }
  } catch (e) {
    print('❌ Decryption failed: $e');
    print('❌ Error type: ${e.runtimeType}');
  }
}
